﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Image2PGM
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_select_origin_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK) 
            {
                text_origin.Text = openFileDialog1.FileName;
            }
        }

        private void btn_select_export_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                text_export.Text = saveFileDialog1.FileName;
            }
        }

        private void btn_convert_Click(object sender, EventArgs e)
        {
            Bitmap bmp;
            
            if (text_origin.Text != "")
            {
                if (text_export.Text != "")
                {
                    File.WriteAllText(text_export.Text, "");
                    var s = File.AppendText(text_export.Text);
                    bmp = new Bitmap(text_origin.Text);
                    //下面是转换代码
                    foreach (char ch in string.Format("P2\n{0} {1}\n255\n", bmp.Width, bmp.Height))
                    {
                        s.Write(ch);
                    }
                    for (int j = 0; j < bmp.Height; j++)
                    {
                        for (int i = 0; i < bmp.Width; i++)
                        {
                            Color p = bmp.GetPixel(i, j);
                            s.Write(((int)((p.R + p.G + p.B) / 3.0)).ToString());
                            s.Write('\n');
                        }
                    }
                    s.Close();
                    MessageBox.Show("转换完成");
                }
                else
                {
                    MessageBox.Show("请先选择导出文件名");
                    return;
                }
                
            }
            else
            {
                MessageBox.Show("请先选择原始图像");
                return;
            }
            
        }
    }
}
